"""
获取可用的模型列表

通过 CommonChoices API 或从现有智能体中提取模型信息
"""
import os
import sys
import json
from collections import defaultdict

# 添加项目路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

from src.llm.hiagent_app.utils.api_client import HiAgentAPIClient
from src.llm.hiagent_app.services.personal_agent_service import PersonalAgentService


def get_models_from_agents():
    """从现有智能体中提取模型信息"""
    service = PersonalAgentService()
    api_client = service.api_client

    print("[方法1] 从现有智能体中提取模型信息...")
    print("=" * 60)

    # 获取智能体列表
    apps, total = service.list_personal_agents()

    if not apps:
        print("[提示] 没有找到现有智能体")
        return {}

    print(f"[信息] 找到 {total} 个智能体，开始提取模型信息...\n")

    # 模型信息字典: {model_id: {"name": model_name, "count": usage_count, "agents": [agent_names]}}
    models = defaultdict(lambda: {"name": "未知", "count": 0, "agents": []})

    for idx, app in enumerate(apps, 1):
        try:
            # 尝试获取草稿配置
            response = api_client.make_request("GetAppSingleModeDraft", {
                "WorkspaceID": api_client.config.DEFAULT_WORKSPACE_ID,
                "AppID": app.app_id
            })

            app_config = response.get("AppConfigDraft", {})
            model_id = app_config.get("ModelID")
            model_name = app_config.get("ModelName", "未知")

            if model_id:
                models[model_id]["name"] = model_name
                models[model_id]["count"] += 1
                models[model_id]["agents"].append(app.name)
                print(f"   [{idx}] {app.name[:30]:30} -> {model_name} ({model_id})")

        except Exception as e:
            # 尝试获取已发布配置
            try:
                response2 = api_client.make_request("GetAppConfig", {
                    "WorkspaceID": api_client.config.DEFAULT_WORKSPACE_ID,
                    "AppID": app.app_id
                })

                app_config_info = response2.get("AppConfigInfo", {})
                model_id = app_config_info.get("ModelID")
                model_name = app_config_info.get("ModelName", "未知")

                if model_id:
                    models[model_id]["name"] = model_name
                    models[model_id]["count"] += 1
                    models[model_id]["agents"].append(app.name)
                    print(f"   [{idx}] {app.name[:30]:30} -> {model_name} ({model_id})")

            except Exception as e2:
                continue

    return dict(models)


def try_common_choices_api():
    """尝试调用 CommonChoices API 获取模型列表"""
    api_client = HiAgentAPIClient()

    print("\n" + "=" * 60)
    print("[方法2] 尝试调用 CommonChoices API...")
    print("=" * 60)

    try:
        response = api_client.make_request("CommonChoices", {
            "WorkspaceID": api_client.config.DEFAULT_WORKSPACE_ID
        })

        print("[成功] CommonChoices API 响应:")
        print(json.dumps(response, indent=2, ensure_ascii=False))

        # 查找可能包含模型信息的字段
        if "ModelChoices" in response:
            print("\n[模型选择列表]:")
            for model in response.get("ModelChoices", []):
                print(f"   - {model}")

        return response

    except Exception as e:
        print(f"[失败] CommonChoices API 调用失败: {e}")
        return None


def print_model_summary(models):
    """打印模型汇总信息"""
    if not models:
        return

    print("\n" + "=" * 60)
    print("模型使用统计汇总:")
    print("=" * 60)

    # 按使用次数排序
    sorted_models = sorted(models.items(), key=lambda x: x[1]["count"], reverse=True)

    for model_id, info in sorted_models:
        print(f"\n模型: {info['name']}")
        print(f"   ID: {model_id}")
        print(f"   使用次数: {info['count']}")
        print(f"   使用的智能体:")
        for agent in info["agents"][:5]:  # 只显示前5个
            print(f"      - {agent}")
        if len(info["agents"]) > 5:
            print(f"      ... 还有 {len(info['agents']) - 5} 个智能体")


def save_models_to_file(models, filename="available_models.json"):
    """将模型信息保存到文件"""
    if not models:
        return False

    try:
        output_path = os.path.join(
            os.path.dirname(__file__),
            filename
        )

        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(models, f, indent=2, ensure_ascii=False)

        print(f"\n[成功] 模型信息已保存到: {output_path}")
        return True

    except Exception as e:
        print(f"[错误] 保存文件失败: {e}")
        return False


def main():
    """主函数"""
    print("=" * 60)
    print("获取可用的模型列表")
    print("=" * 60)
    print()

    # 方法1: 从现有智能体中提取
    models = get_models_from_agents()

    # 方法2: 尝试 CommonChoices API
    try_common_choices_api()

    # 打印汇总
    print_model_summary(models)

    # 保存到文件
    if models:
        save_models_to_file(models)

    # 提供使用建议
    print("\n" + "=" * 60)
    print("使用建议:")
    print("=" * 60)
    print("1. 上面列出的 ModelID 都是已验证可用的")
    print("2. 创建新智能体时，可以参考这些 ModelID")
    print("3. 模型名称和 ID 的对应关系已保存到文件")
    print("4. 如果需要使用新模型，建议先在系统界面中测试")
    print("=" * 60)


if __name__ == "__main__":
    main()
